/**
 * 弹框
 * 调用方法：
 * import { modalOpen, modalClose } from '../../util/global';
 * modalOpen({
 *   visible: true,
 *   Type: () => <Gallery index={1} images={[{ url: '' }]} close={modalClose} />,
 * });
 */

import React, { useState, useEffect, ReactElement } from 'react';
import { View, DeviceEventEmitter } from 'react-native';

import { GLOBAL_MODEL, isIOS } from '../../constant';
import Notch, { NotchType } from '../Notch';
import styles from './style';
import Blur from '../Blur';
import navigator from '../../util/navigator';
import { getRouteType, RouteType } from '../../config/route';

export interface Model {
  visible?: boolean; // 是否打开弹框
  Type?: () => ReactElement; // 模态框内容
  needClose?: boolean; // 是否需要点击背景关闭
  closeAction?: () => void; // 点击背景关闭回调
  needBack?: boolean; // 是否背景色
  needBlur?: boolean; // 是否毛玻璃
  needBackView?: boolean; // 是否需要背景层
}

const init = {
  visible: false,
  Type: (): ReactElement => <View />,
  needClose: false,
  closeAction: (): void => {},
  needBack: false,
  needBlur: false,
  needBackView: true
};

const Modal = (): ReactElement | null => {
  const [state, setState] = useState<Model>(init);

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      GLOBAL_MODEL,
      (param): void => {
        setState({ ...init, ...param });
      }
    );

    return (): void => {
      subscription.remove();
    };
  }, [state]);

  const {
    visible,
    Type,
    needClose,
    closeAction,
    needBack,
    needBlur,
    needBackView
  } = state;
  if (!visible) return null;

  const currentRoute = navigator.getCurrentRoute();
  const routeType = getRouteType(currentRoute.routeName);

  const modal = (
    <Notch
      type={routeType === RouteType.LandScape ? NotchType.Left : NotchType.Top}
      style={[
        styles.container,
        needBack ? styles.back : {},
        needBack && needBlur && isIOS
          ? { backgroundColor: 'rgba(0, 0, 0, 0.7)' }
          : {}
      ]}
      onResponderEnd={(): void => {
        setState(init);
        if (closeAction) closeAction();
      }}
      onStartShouldSetResponder={(): boolean => needClose || false}
    >
      {needBlur && isIOS && <Blur />}
      {Type && <Type />}
    </Notch>
  );

  if (!needBackView) {
    return Type ? <Type /> : null;
  }

  if (needBlur && !isIOS) {
    return <Blur>{modal}</Blur>;
  }

  return modal;
};

export default Modal;
